<template>
  <view class="account-binding">
    <view class="binding-header">
      <text class="title">账户绑定</text>
      <text class="subtitle">绑定后可在小程序和H5端同步使用</text>
    </view>
    
    <view class="binding-content">
      <!-- 当前账户信息 -->
      <view class="current-account">
        <view class="account-info">
          <image 
            class="avatar" 
            :src="userInfo.avatar_url || '/static/images/default-avatar.png'"
            mode="aspectFill"
          />
          <view class="info">
            <text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
            <text class="account-type">{{ accountTypeText }}</text>
          </view>
        </view>
        
        <view class="binding-status">
          <view class="status-item" :class="{ 'bound': hasWechat }">
            <text class="icon">📱</text>
            <text class="label">微信</text>
            <text class="status">{{ hasWechat ? '已绑定' : '未绑定' }}</text>
          </view>
          
          <view class="status-item" :class="{ 'bound': hasPhone }">
            <text class="icon">📞</text>
            <text class="label">手机号</text>
            <text class="status">{{ hasPhone ? userInfo.phone : '未绑定' }}</text>
          </view>
        </view>
      </view>
      
      <!-- 绑定操作 -->
      <view class="binding-actions">
        <!-- 绑定手机号 -->
        <view class="action-item" v-if="!hasPhone">
          <view class="action-header">
            <text class="action-title">绑定手机号</text>
            <text class="action-desc">绑定后可使用手机号登录</text>
          </view>
          
          <view class="phone-binding" v-if="showPhoneBinding">
            <view class="input-group">
              <input 
                class="form-input" 
                type="tel" 
                placeholder="请输入手机号" 
                v-model="phoneForm.phone"
                maxlength="11"
              />
            </view>
            
            <view class="input-group">
              <view class="code-input-row">
                <input 
                  class="form-input code-input" 
                  type="number" 
                  placeholder="验证码" 
                  v-model="phoneForm.code"
                  maxlength="6"
                />
                <button 
                  class="send-code-btn" 
                  @click="sendPhoneCode"
                  :disabled="!canSendPhoneCode"
                >
                  {{ phoneCodeButtonText }}
                </button>
              </view>
            </view>
            
            <view class="action-buttons">
              <button class="cancel-btn" @click="cancelPhoneBinding">取消</button>
              <button 
                class="confirm-btn" 
                @click="confirmPhoneBinding"
                :disabled="!canConfirmPhone"
              >
                确认绑定
              </button>
            </view>
          </view>
          
          <button 
            class="bind-btn" 
            @click="startPhoneBinding"
            v-else
          >
            绑定手机号
          </button>
        </view>
        
        <!-- 绑定微信 -->
        <view class="action-item" v-if="!hasWechat">
          <view class="action-header">
            <text class="action-title">绑定微信</text>
            <text class="action-desc">绑定后可使用微信登录</text>
          </view>
          
          <!-- #ifdef MP-WEIXIN -->
          <button class="bind-btn" @click="bindWechat">
            绑定微信账号
          </button>
          <!-- #endif -->
          
          <!-- #ifdef H5 -->
          <view class="wechat-tip">
            <text>请在微信小程序中绑定微信账号</text>
          </view>
          <!-- #endif -->
        </view>
        
        <!-- 数据同步状态 -->
        <view class="sync-status" v-if="hasWechat && hasPhone">
          <view class="sync-header">
            <text class="sync-title">数据同步</text>
            <text class="sync-desc">账户数据已在各端同步</text>
          </view>
          
          <view class="sync-info">
            <view class="sync-item">
              <text class="sync-label">积分余额</text>
              <text class="sync-value">{{ userInfo.points || 0 }} 分</text>
            </view>
            
            <view class="sync-item">
              <text class="sync-label">会员等级</text>
              <text class="sync-value">{{ memberLevelText }}</text>
            </view>
            
            <view class="sync-item">
              <text class="sync-label">同步状态</text>
              <text class="sync-value" :class="syncStatusClass">{{ syncStatusText }}</text>
            </view>
            
            <view class="sync-item">
              <text class="sync-label">最后同步</text>
              <text class="sync-value">{{ lastSyncTime }}</text>
            </view>
          </view>
          
          <view class="sync-actions">
            <button class="sync-btn" @click="checkSyncStatus" :disabled="checkingSync">
              {{ checkingSync ? '检查中...' : '检查同步' }}
            </button>
            <button class="sync-btn primary" @click="forceSyncData" :disabled="syncing">
              {{ syncing ? '同步中...' : '立即同步' }}
            </button>
          </view>
        </view>
        
        <!-- 跨端登录记录 -->
        <view class="login-history" v-if="hasWechat || hasPhone">
          <view class="history-header">
            <text class="history-title">登录记录</text>
            <text class="history-desc">最近的跨端登录记录</text>
          </view>
          
          <view class="history-list" v-if="loginHistory.length > 0">
            <view 
              class="history-item" 
              v-for="(login, index) in loginHistory" 
              :key="index"
            >
              <view class="login-platform">
                <text class="platform-icon">{{ login.platform === 'miniprogram' ? '📱' : '🌐' }}</text>
                <text class="platform-name">{{ login.platform === 'miniprogram' ? '小程序' : 'H5' }}</text>
              </view>
              <view class="login-info">
                <text class="login-time">{{ formatTime(login.loginTime) }}</text>
                <text class="login-ip">{{ login.ip }}</text>
              </view>
            </view>
          </view>
          
          <view class="no-history" v-else>
            <text>暂无登录记录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'AccountBinding',
  data() {
    return {
      showPhoneBinding: false,
      phoneForm: {
        phone: '',
        code: ''
      },
      phoneCountdown: 0,
      sendingPhoneCode: false,
      syncStatus: null,
      checkingSync: false,
      syncing: false,
      loginHistory: []
    }
  },
  
  computed: {
    ...mapGetters('auth', [
      'userInfo',
      'hasPhone',
      'hasWechat',
      'memberLevel'
    ]),
    
    // 账户类型文本
    accountTypeText() {
      if (this.hasWechat && this.hasPhone) {
        return '微信+手机号账户'
      } else if (this.hasWechat) {
        return '微信账户'
      } else if (this.hasPhone) {
        return '手机号账户'
      } else {
        return '游客账户'
      }
    },
    
    // 会员等级文本
    memberLevelText() {
      const levelMap = {
        normal: '普通会员',
        silver: '白银会员',
        gold: '黄金会员'
      }
      return levelMap[this.memberLevel] || '普通会员'
    },
    
    // 最后同步时间
    lastSyncTime() {
      return new Date().toLocaleString()
    },
    
    // 是否可以发送手机验证码
    canSendPhoneCode() {
      return /^1[3-9]\d{9}$/.test(this.phoneForm.phone) && this.phoneCountdown === 0
    },
    
    // 手机验证码按钮文本
    phoneCodeButtonText() {
      if (this.sendingPhoneCode) return '发送中...'
      if (this.phoneCountdown > 0) return `${this.phoneCountdown}s`
      return '发送验证码'
    },
    
    // 是否可以确认绑定手机
    canConfirmPhone() {
      return /^1[3-9]\d{9}$/.test(this.phoneForm.phone) && 
             this.phoneForm.code.length === 6
    },
    
    // 同步状态文本
    syncStatusText() {
      if (!this.syncStatus) return '未知'
      return this.syncStatus.synced ? '已同步' : '需要同步'
    },
    
    // 同步状态样式类
    syncStatusClass() {
      if (!this.syncStatus) return ''
      return this.syncStatus.synced ? 'synced' : 'need-sync'
    }
  },
  
  methods: {
    // 开始绑定手机号
    startPhoneBinding() {
      this.showPhoneBinding = true
      this.phoneForm = { phone: '', code: '' }
    },
    
    // 取消绑定手机号
    cancelPhoneBinding() {
      this.showPhoneBinding = false
      this.phoneForm = { phone: '', code: '' }
      this.phoneCountdown = 0
    },
    
    // 发送手机验证码
    async sendPhoneCode() {
      if (!this.canSendPhoneCode) return
      
      try {
        this.sendingPhoneCode = true
        
        await this.$store.dispatch('auth/sendSmsCode', this.phoneForm.phone)
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        this.startPhoneCountdown()
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      } finally {
        this.sendingPhoneCode = false
      }
    },
    
    // 开始手机验证码倒计时
    startPhoneCountdown() {
      this.phoneCountdown = 60
      const timer = setInterval(() => {
        this.phoneCountdown--
        if (this.phoneCountdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    
    // 确认绑定手机号
    async confirmPhoneBinding() {
      if (!this.canConfirmPhone) return
      
      try {
        uni.showLoading({ title: '绑定中...' })
        
        await this.$store.dispatch('auth/bindPhone', {
          phone: this.phoneForm.phone,
          code: this.phoneForm.code
        })
        
        uni.hideLoading()
        
        uni.showToast({
          title: '绑定成功',
          icon: 'success'
        })
        
        this.showPhoneBinding = false
        this.phoneForm = { phone: '', code: '' }
        
        // 触发绑定成功事件
        this.$emit('bind-success', 'phone')
        
      } catch (error) {
        uni.hideLoading()
        console.error('绑定手机号失败:', error)
        uni.showToast({
          title: error.message || '绑定失败',
          icon: 'none'
        })
      }
    },
    
    // 绑定微信
    async bindWechat() {
      try {
        // #ifdef MP-WEIXIN
        uni.showLoading({ title: '绑定中...' })
        
        // 获取微信登录信息
        const { code, userInfo } = await this.$wechat.wechatLoginFlow()
        
        // 调用绑定接口
        await this.$store.dispatch('auth/bindWechat', {
          code,
          userInfo: this.$wechat.formatWechatUserInfo(userInfo)
        })
        
        uni.hideLoading()
        
        uni.showToast({
          title: '绑定成功',
          icon: 'success'
        })
        
        // 触发绑定成功事件
        this.$emit('bind-success', 'wechat')
        // #endif
        
      } catch (error) {
        uni.hideLoading()
        console.error('绑定微信失败:', error)
        uni.showToast({
          title: error.message || '绑定失败',
          icon: 'none'
        })
      }
    },
    
    // 检查同步状态
    async checkSyncStatus() {
      if (this.checkingSync) return
      
      try {
        this.checkingSync = true
        
        const response = await this.$store.dispatch('auth/checkSyncStatus')
        this.syncStatus = response.data
        
        uni.showToast({
          title: this.syncStatus.synced ? '数据已同步' : '数据需要同步',
          icon: this.syncStatus.synced ? 'success' : 'none'
        })
        
      } catch (error) {
        console.error('检查同步状态失败:', error)
        uni.showToast({
          title: '检查失败',
          icon: 'none'
        })
      } finally {
        this.checkingSync = false
      }
    },
    
    // 强制同步数据
    async forceSyncData() {
      if (this.syncing) return
      
      try {
        this.syncing = true
        uni.showLoading({ title: '同步中...' })
        
        await this.$store.dispatch('auth/forceSyncData')
        
        // 重新检查同步状态
        await this.checkSyncStatus()
        
        uni.hideLoading()
        uni.showToast({
          title: '同步成功',
          icon: 'success'
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('强制同步失败:', error)
        uni.showToast({
          title: error.message || '同步失败',
          icon: 'none'
        })
      } finally {
        this.syncing = false
      }
    },
    
    // 获取登录记录
    async getLoginHistory() {
      try {
        const response = await this.$store.dispatch('auth/getCrossPlatformState')
        
        if (response.data && response.data.recentLogins) {
          this.loginHistory = response.data.recentLogins.slice(0, 5) // 只显示最近5条
        }
        
      } catch (error) {
        console.error('获取登录记录失败:', error)
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return time.toLocaleDateString()
      }
    }
  },
  
  async mounted() {
    // 初始化时获取同步状态和登录记录
    if (this.hasWechat && this.hasPhone) {
      await this.checkSyncStatus()
      await this.getLoginHistory()
    }
  }
}
</script>

<style lang="scss" scoped>
.account-binding {
  padding: 40rpx;
}

.binding-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.binding-content {
  background: white;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.current-account {
  margin-bottom: 60rpx;
}

.account-info {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  
  .avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    margin-right: 30rpx;
  }
  
  .info {
    flex: 1;
    
    .nickname {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .account-type {
      display: block;
      font-size: 24rpx;
      color: #666;
    }
  }
}

.binding-status {
  display: flex;
  gap: 40rpx;
}

.status-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 20rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  
  &.bound {
    background: #e8f5e8;
  }
  
  .icon {
    display: block;
    font-size: 48rpx;
    margin-bottom: 16rpx;
  }
  
  .label {
    display: block;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 8rpx;
  }
  
  .status {
    display: block;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
}

.binding-actions {
  .action-item {
    margin-bottom: 40rpx;
    padding: 40rpx;
    background: #f8f8f8;
    border-radius: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.action-header {
  margin-bottom: 30rpx;
  
  .action-title {
    display: block;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .action-desc {
    display: block;
    font-size: 24rpx;
    color: #666;
  }
}

.phone-binding {
  .input-group {
    margin-bottom: 30rpx;
  }
  
  .form-input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #e5e5e5;
    border-radius: 12rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
    
    &:focus {
      border-color: #007aff;
    }
  }
  
  .code-input-row {
    display: flex;
    gap: 20rpx;
    
    .code-input {
      flex: 1;
    }
    
    .send-code-btn {
      width: 160rpx;
      height: 80rpx;
      background: #007aff;
      color: white;
      border: none;
      border-radius: 12rpx;
      font-size: 24rpx;
      
      &:disabled {
        background: #ccc;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
    margin-top: 40rpx;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 80rpx;
      border: none;
      border-radius: 12rpx;
      font-size: 28rpx;
    }
    
    .cancel-btn {
      background: #f5f5f5;
      color: #666;
    }
    
    .confirm-btn {
      background: #007aff;
      color: white;
      
      &:disabled {
        background: #ccc;
      }
    }
  }
}

.bind-btn {
  width: 100%;
  height: 80rpx;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.wechat-tip {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 24rpx;
}

.sync-status {
  background: #e8f5e8;
  
  .sync-header {
    margin-bottom: 30rpx;
    
    .sync-title {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .sync-desc {
      display: block;
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .sync-info {
    margin-bottom: 30rpx;
    
    .sync-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
      
      &:last-child {
        border-bottom: none;
      }
      
      .sync-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .sync-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        
        &.synced {
          color: #52c41a;
        }
        
        &.need-sync {
          color: #ff4d4f;
        }
      }
    }
  }
  
  .sync-actions {
    display: flex;
    gap: 20rpx;
    
    .sync-btn {
      flex: 1;
      height: 70rpx;
      border: 2rpx solid #007aff;
      background: white;
      color: #007aff;
      border-radius: 12rpx;
      font-size: 26rpx;
      
      &.primary {
        background: #007aff;
        color: white;
      }
      
      &:disabled {
        background: #f5f5f5;
        color: #ccc;
        border-color: #e5e5e5;
      }
    }
  }
}

.login-history {
  margin-top: 40rpx;
  padding: 40rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  
  .history-header {
    margin-bottom: 30rpx;
    
    .history-title {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .history-desc {
      display: block;
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .history-list {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 0;
      border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
      
      &:last-child {
        border-bottom: none;
      }
      
      .login-platform {
        display: flex;
        align-items: center;
        
        .platform-icon {
          font-size: 32rpx;
          margin-right: 16rpx;
        }
        
        .platform-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
      }
      
      .login-info {
        text-align: right;
        
        .login-time {
          display: block;
          font-size: 24rpx;
          color: #666;
          margin-bottom: 4rpx;
        }
        
        .login-ip {
          display: block;
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }
  
  .no-history {
    text-align: center;
    padding: 60rpx 0;
    color: #999;
    font-size: 24rpx;
  }
}
</style>